package com.abe.libquick.widget;

import android.app.Activity;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;

import com.abe.libquick.utils.ScreenHelper;

import java.lang.reflect.Method;

public class BottomSoftBar {

    private View mViewObserved;//被监听的视图
    private int usableHeightPrevious;//视图变化前的可用高度

    private BottomSoftBar(View viewObserving, final Activity activity) {
        mViewObserved = viewObserving;
        //给View添加全局的布局监听器
        mViewObserved.getViewTreeObserver().addOnGlobalLayoutListener(() -> resetLayoutByUsableHeight(activity));
    }


    /**
     * 关联要监听的视图
     */
    public static void assistActivity(View viewObserving, Activity activity) {
        new BottomSoftBar(viewObserving, activity);
    }

    /**
     * dpi 通过反射，获取包含虚拟键的整体屏幕高度
     * height 获取屏幕尺寸，但是不包括虚拟功能高度
     */
    public static int getHasVirtualKey(Activity activity) {
        int dpi = 0;
        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        @SuppressWarnings("rawtypes")
        Class c;
        try {
            c = Class.forName("android.view.Display");
            @SuppressWarnings("unchecked")
            Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
            method.invoke(display, dm);
            dpi = dm.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }


        int height = activity.getWindowManager().getDefaultDisplay().getHeight();
        return dpi - height;
    }

    private void resetLayoutByUsableHeight(Activity activity) {
        int usableHeightNow = ScreenHelper.getScreenHeight();
        //比较布局变化前后的View的可用高度
        if (usableHeightNow != usableHeightPrevious) {
            //如果两次高度不一致
            //将当前的View的可用高度设置成View的实际高度
            mViewObserved.setPadding(0, 0, 0, getHasVirtualKey(activity));
            mViewObserved.requestLayout();//请求重新布局
            usableHeightPrevious = usableHeightNow;
        }
    }
}